package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQueryObject;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpotServiceImpl implements ISpotService {

    @Autowired
    private SpotRepository spotRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Spot spot) {
        spot.setId(null);
        spotRepository.save(spot);
    }

    @Override
    public void delete(String id) {
        spotRepository.deleteById(id);
    }

    @Override
    public void update(Spot spot) {
        spotRepository.save(spot);
    }

    @Override
    public Spot get(String id) {
        return spotRepository.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {
        return spotRepository.findAll();
    }

    @Override
    public Page<Spot> query(SpotQueryObject qo) {
        // 创建拼接对象
        Query query = new Query();
        // 使用PageRequest.of,传入当前页 - 1 (记得-1, 因为当前页从0开始), 页面显示条数, 排序规则, 排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, qo, query, pageable, Spot.class);
    }


}
